package com.duowei.diandan.fragment.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.text.InputType;
import android.view.Gravity;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.duowei.diandan.BuildConfig;
import com.duowei.diandan.R;
import com.duowei.diandan.activity.SettingsActivity;

/**
 * 用户进入设置时, 弹出认证对话框
 */
public class UserAuthDialogFragment extends AppCompatDialogFragment {

    private Context mContext;
    private EditText passwordView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getContext();
    }

    @SuppressLint("SetTextI18n")
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        passwordView = new EditText(getContext());
        passwordView.setInputType(InputType.TYPE_CLASS_NUMBER);
        passwordView.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
        passwordView.setLayoutParams(lp);

        if (BuildConfig.DEBUG) {
            passwordView.setText(R.string.password);
        }

        AlertDialog dialog = new AlertDialog.Builder(mContext)
                .setTitle("请输入密码")
                .setView(passwordView)
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", null)
                .show();

        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
            String password = passwordView.getText().toString();

            if (getString(R.string.password).equals(password)) {
                SettingsActivity.openSettingsActivity(getContext());

                dismiss();

            } else {
                Toast.makeText(mContext, "密码错误!", Toast.LENGTH_SHORT).show();
            }
        });

        return dialog;
    }
}
